package cn.chainco.cts.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import com.opensymphony.xwork2.ActionSupport;

import cn.chainco.cts.iservice.CommonManager;
import cn.chainco.cts.iservice.ICompanyManager;
import cn.chainco.cts.iservice.IEmployeeManager;
import cn.chainco.cts.iservice.IUserManager;
import cn.chainco.cts.jdo.Company;
import cn.chainco.cts.jdo.Employee;
import cn.chainco.cts.jdo.User;
import cn.chainco.cts.utils.CommUtils;
import cn.chainco.cts.utils.Constants;
import cn.chainco.cts.utils.CookieUtil;
import cn.chainco.cts.utils.MD5;
import cn.chainco.cts.utils.MyMailSender;
import cn.chainco.cts.utils.TimeUtil;
import cn.chainco.cts.utils.VarData;
import cn.chainco.cts.utils.ZoomImage;
import cn.chainco.cts.utils.OperateImage;
import cn.chainco.cts.utils.query.OP;
import cn.chainco.cts.utils.query.QueryParam;

@SuppressWarnings("unchecked")
@InterceptorRef("ctsInterceptors")
public class UserAction extends ActionSupport{
    
	private static final long serialVersionUID = -5938135224254197308L;
	private User user;
	private CommonManager commonManager;
    private IUserManager userManager;
    private ICompanyManager companyManager;
    private IEmployeeManager employeeManager;
    
    // 图片 
    private List<File> Filedata;
	private List<String> FiledataFileName;
	private List<String> FiledataContentType;
	private String name;
    
    @Action("toLogin")
    public String toLogin(){
      return "login";	
    }
    
	/**
	 * 用户注销
	 */
    @Action("logout")
	public String logout(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		request.getSession().invalidate();
		request.getSession().setAttribute("logout", "logout");
		Cookie[] cookies = request.getCookies();

		if(cookies != null){
			for(int i = 0; i < cookies.length; i++){
				String name = cookies[i].getName();
				if(CommUtils.isValidStr(name) && name.startsWith("cts_")){
					cookies[i].setMaxAge(0);
					cookies[i].setPath("/");
					response.addCookie(cookies[i]);
				}
			}
		}
		
		try {
			response.sendRedirect("");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "index";
	}
    
	/**
	 * 用户登录
	 */
    @Action("login")
	public void login(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		// HttpSession session = request.getSession();
		try{
			String username = request.getParameter("username");
			String userpass = request.getParameter("userpass");
			
			int code = 1;
			user = userManager.findByNameAndPass(username.trim(), MD5.toMD5(userpass.trim()));
			if(user == null){
				code = -1; // 用户名或密码错
				request.setAttribute("code", code);
			}else if(user.getStatus() == 2){
				code = -1; // 用户名或密码错
			}else{
				if( user.getStatus() != null && user.getStatus() == 1){
					code = -2; // 用户禁用
					request.setAttribute("code", code);
				}else{

					if(VarData.adminName.equals(user.getUserName())){
						code = -3;
					}
					
					String loginFlag = request.getParameter("loginFlag");
					int times = 0;
					if(loginFlag != null && loginFlag.equals("1")){
						times = 14 * 24 * 60 * 60;
					}else{
						times = -1;
					}
					
					ActionUtil.addUserToCookie(user, times);
					String locale = request.getLocale().toString(); // 得到浏览器的语言
					String _locale = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_locale");
					if("".equals(_locale) || _locale.length() <=0 || locale.equals("zh_CH")){
						CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_locale", "zh_CH", "/", times);
					}
					
					// cts_employeecpyid
				    if(code == 1 && user !=null){
				    	Company _company = this.companyManager.findCompayByUser(user);
				    	if(_company !=null){
				    		// 员工id
				    		Employee _employee = this.employeeManager.findEmployeeByUser(user, _company);
				    		if(_employee!=null){
				    			ActionUtil.addEmployeeToCookie(_employee, times);
				    			//CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_employeecpyid", emp_.getId()+"" , "/", times);
				    			//CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_employeetype", emp_.getType()+"" , "/", times);
				    		}
				    		
				    		ActionUtil.addCompanyToCookie(_company, times);
				    		//CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_userid", user.getId()+"" , "/", times);
				    		//CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_companyid", adminCompany.getId()+"" , "/", times);
				    		//CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_emplcpyid", adminCompany.getId() +"" , "/", times);
				    		//CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_companyName", adminCompany.getName() , "/", times);
				    		//CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_companyPrefix", adminCompany.getPrefix(), "/", times);
				    		//CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_companyLogoPath", adminCompany.getLogoPath(), "/", times);
				    		//CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_companyStatus", adminCompany.getStatus().toString() , "/", times);
				    	}
				    }
				}
			}
			response.setCharacterEncoding("UTF-8");
			response.setContentType("html/text;charset=utf-8");
			try{
			   response.getWriter().print(code);
			}catch(IOException e){
				e.printStackTrace();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 到用户页面
	 *
	 */
	@Action("toUser")
	public String toUser(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String userId = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_userid");
		String toType = request.getParameter("toType");
		
		
		if(toType!=null && toType.equals("1")){
			
			if(CommUtils.isCorrectNumber(userId)){
				Long l_userId = Long.valueOf(userId);
				user = this.commonManager.findEntityByPK(User.class, l_userId);
			}
			
			return "personInfo";
		}else{
			return "user";
		}
		
	}
	
	/**
	 * 保存用户
	 *
	 */
	@Action("saveUser")
	public void saveUser(){
		Date createTime = new Date();
		HttpServletRequest request = ServletActionContext.getRequest();
		String isTimeUp = request.getParameter("isTimeUp");
		String timeFileName = request.getParameter("timeFileName");
		String timePasswd = request.getParameter("timePasswd");
		
		try{
			if(user!=null){
				if(user!=null && user.getId()!=0){
					if(user.getUserPass().trim().trim().equals("")){
						user.setUserPass(timePasswd);
					}else{
						user.setUserPass(MD5.toMD5(user.getUserPass()));
					}
					
				    this.commonManager.modifyEntity(user);
				    ActionUtil.outputData("2");
				}else{
					Long result = 0L;
					List<QueryParam>  paramList = new ArrayList<QueryParam>();
					QueryParam param = new QueryParam();
					param.setField("userName");
					param.setOp(OP.equal);
					param.setValue(new Object[]{user.getUserName()});
					paramList.add(param);
					List<User> userlist  = this.commonManager.findByCustomized(User.class, paramList, null);
					
					user.setUserPass(MD5.toMD5(user.getUserPass()));
					user.setCreateTime(createTime);
					if(userlist.size() > 0 && userlist.get(0).getStatus() == 2){ // 修改临时用户
						User __user = userlist.get(0);
						__user.setCreateTime(new Date());
						__user.setLogoPath(user.getLogoPath());
						__user.setStatus(0);
						__user.setUserPass(user.getUserPass());
						this.commonManager.modifyEntity(__user);
						user = __user;
						result = __user.getId();
					}else{
						result = this.commonManager.saveEntity(user);
						user = this.commonManager.findEntityByPK(User.class, result);
					}
					
					try {
						if(timeFileName!=null  && isTimeUp!=null && isTimeUp.equals("true")){
							ActionUtil aUtil = new ActionUtil();
							String from = Constants.BASE_DIR + File.separator + Constants.USER_FILENAME + File.separator + "timeUserFile" + File.separator + timeFileName;
							String to  =  Constants.BASE_DIR + File.separator + Constants.USER_FILENAME + File.separator +  File.separator + result;
							aUtil.reSetPath(from, to);
						}
					} catch (RuntimeException e) {
						e.printStackTrace();
					}
					
					if(result>0){
						ActionUtil.addUserToCookie(user, -1);
						ActionUtil.outputData("1");
					}else{
						ActionUtil.outputData("0");
					}
				}
				
				
			}else{
				ActionUtil.outputData("0");
			}
		}catch(Exception e){
			ActionUtil.outputData("0");
			e.printStackTrace();
		}
		
	}

	/**
	 * 
	 *模糊查找用户，根据用户名
	 */
	@Action("fuzzyUser")
	public void fuzzyUserByName(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		
		String name = request.getParameter("name");
		String userName = CookieUtil.getCookieValue(request, "cts_username");
		
		if(name !=null && name!=""){
			List<User> userList = this.userManager.findByName(name);
			String jStr="";
			
			if(userList.size() > 0){
				for (User user : userList) {
					if(user.getStatus()!=2 && !user.getUserName().equals(userName) && !user.getUserName().equals(VarData.adminName)){
						jStr += "{'userId':'"+user.getId()+"','userName':'"+user.getUserName()+"'},";
					}
				}
				
				if(jStr.trim().length() > 0){
					jStr = jStr.substring(0 , jStr.length()-1);
				}
			}
			
			String jsonStr = "["+jStr+"]";
			ActionUtil.outputData(jsonStr);
		}
		
	}
	
	/**
	 * 查找用户
	 */
	@Action("findUserByType")
	public void findUserByType(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String type = request.getParameter("type"); // 1.根据用户id , 2.根据用户名
		String returnUid = request.getParameter("returnUid"); // 是否返回用户id:0.是,1.否
		String sta = request.getParameter("sta"); // 用户状态: 0正常 , 1禁用 , 2临时(当多个 , 逗号分隔)
		String userName = request.getParameter("username");
		String sql = "";
		try {
			if(type.equals("1")){
				sql= "select * from cts_user where 1=1 and userName='"+userName+"'";
			}else if(type.equals("2")){
				String id = request.getParameter("id");
				sql= "select * from cts_user where 1=1 and id='"+id+"'";
			}
			
			if(sta!=null && !sta.trim().equals("")){
				sql += " and status in ("+sta+")";
			}
			
			List<User> userList = this.userManager.findSqlByElist(sql, User.class, null);
			if(userList.size()>0){
			  if(returnUid!=null && returnUid.equals("0")){
				  Long uId = userList.get(0).getId();
				  ActionUtil.outputData(uId);
			  }else{
				  ActionUtil.outputData("1");
			  }
			}else{
				ActionUtil.outputData("0"); 
			}
		} catch (RuntimeException e) {
			ActionUtil.outputData("-1"); // 出错
			e.printStackTrace();
		}
	}
	
	/**
	 * 到找回密码的页面
	 * @return
	 */
	@Action("tofindPwdPage")
	public String tofindPwdPage(){
		HttpServletRequest request = ServletActionContext.getRequest();
		//HttpSession session = ActionUtil.getSession();
		String userId = request.getParameter("ucode");
		String userName = request.getParameter("uncode");
		String setup = request.getParameter("setup");
		String codeKey = request.getParameter("codekey");
		
		// 路径是否有效
		if(setup!=null && setup.equals("2") && CommUtils.isCorrectNumber(userId)){
			User _user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId));
			if(_user!=null && _user.getFindCode().equals(codeKey)){
				request.setAttribute("isOnTime", 1);  // 验证号没有过期
			}
		}
		
		request.setAttribute("userId", userId);
		request.setAttribute("userName", userName);
		request.setAttribute("setup", setup);
		
		return "findPassword";
	}
	
	/**
	 * 找回密码
	 *
	 */
	@Action("findPassword")
	public void findPassword(){
		HttpServletRequest request = ServletActionContext.getRequest();
		//HttpSession session = ActionUtil.getSession();
		
		String userId = request.getParameter("userId");
		String pwd = request.getParameter("password");
		
		int code = 0;
		if(CommUtils.isCorrectNumber(userId) && pwd!=null && !"".equals(pwd)){
			User user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId));
			if(!user.getFindCode().trim().equals("") && user.getFindCode().trim().length() > 0){
				user.setFindCode("");
				user.setUserPass(MD5.toMD5(pwd));
				this.commonManager.modifyEntity(user);
				code = 1;
			}else{
				code = 2; // 过期
			}
		}
		
		ActionUtil.outputData(code);
	}
	
	
	/**
	 * 发送找回密码的邮件
	 *
	 */
	@Action("sendPassword")
	public void sendPassword(){
		HttpServletRequest request = ServletActionContext.getRequest();
		//HttpSession session = ActionUtil.getSession();
		
 		String userName = request.getParameter("userName");
		String userId = request.getParameter("userId");
		String email = request.getParameter("email");
		
		try {
			if(email!=null && userName!=null && CommUtils.isCorrectNumber(userId)){
				// 保存验证码
				int codeKey = new Random().nextInt(1000000);
				User user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId));
				user.setFindCode(String.valueOf(codeKey));
				this.commonManager.modifyEntity(user);
				
				String content = "";
				String path = request.getContextPath();
				String sendTime = TimeUtil.getYYYY_MM_DDHHMM(new Date());
				String fromEail = VarData.fromEmail;
				String emailPassword = VarData.emailPassword;
				String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
				
				String url = basePath + "tofindPwdPage?ucode="+userId+"&uncode="+userName+"&setup=2&codekey="+codeKey;
				content += "<font style='font-size:14px;'>cts系统找回密码</font><br/>";
				content += "<font>点击这链接找回密码</font><br/>";
				content += "<a href='"+ url +"' style='color:red;'>"+ url +"</a><br/>";
				content += "发送时间：" + sendTime;
				
				MyMailSender.sendMail(fromEail, emailPassword, email , "cts找回密码", "cts找回密码" , content);
				ActionUtil.outputData("1");
			}else{
				ActionUtil.outputData("0");
			}
		} catch (Exception e) {
			ActionUtil.outputData("0");
			e.printStackTrace();
		}
	}
	
	// Image Tools
	/**
	 * 到图片上传页面
	 * @return
	 */
	@Action("toImageTool")
	public String toImageTool(){
		HttpServletRequest request = ServletActionContext.getRequest();
		User user = null;
		Company company = null;
		
		String userId = request.getParameter("userid");
		String companyid = request.getParameter("companyid");
		String uptype = request.getParameter("uptype"); // 1.用户 , 2.公司
		String reload = request.getParameter("reload"); // 是否刷新页面 1.是 
		
		String fileBookName = ""; // 文件夹名
		String filePath = ""; // 图片路径
		boolean isTimeFile = false;
		
		if(userId == null || userId == ""){
			userId = CookieUtil.getCookieValue(request, "cts_userid");
		}
		
		if(companyid == null || companyid == ""){
			companyid = CookieUtil.getCookieValue(request, "cts_companyid");
		}
		
		// 用户
		if(CommUtils.isCorrectNumber(userId)){
			user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId));
		}
		
		if(CommUtils.isCorrectNumber(companyid)){
			company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyid));
		}
		// 临时文件夹(记录在cookie)
		if( (user == null && uptype.equals("1")) || (company==null && uptype.equals("2")) ){
			fileBookName = CookieUtil.getCookieValue(request, "cts_regFile");
			if(fileBookName.equals(null) || fileBookName.equals("")){
				int time = 24 * 60 * 60;
				fileBookName = "regFile_" + System.currentTimeMillis();
				CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_regFile", fileBookName , "/", time);
			}
			
			isTimeFile = true;
		}else{ // 用户|公司文件夹
			if(uptype.equals("1")){
				fileBookName = user.getId()+"";
			}else if(uptype.equals("2")){
				fileBookName = companyid;
			}
		}
		
		
		if(uptype.equals("1")){
			filePath = ServletActionContext.getServletContext().getRealPath(
					File.separator + Constants.BASE_DIR + File.separator + 
					Constants.USER_FILENAME + File.separator + fileBookName);
			
			if(isTimeFile == true){ // 临时文件夹
				filePath = ServletActionContext.getServletContext().getRealPath(
						File.separator + Constants.BASE_DIR + File.separator + 
						Constants.USER_FILENAME + File.separator+ "timeUserFile" + File.separator  + fileBookName);
			}
		}else if(uptype.equals("2")){  /** 公司图片 **/
			filePath = ServletActionContext.getServletContext().getRealPath(
					File.separator + Constants.BASE_DIR + File.separator + 
					Constants.COMPANY_FILENAME + File.separator + fileBookName);
			
			if(isTimeFile == true){ // 临时文件夹
				filePath = ServletActionContext.getServletContext().getRealPath(
						File.separator + Constants.BASE_DIR + File.separator + 
						Constants.COMPANY_FILENAME + File.separator+ "timeUserFile" + File.separator  + fileBookName);
			}
		}
		
		File file = new File(filePath);
		if(!file.exists()){
			file.mkdirs();
		}
		
		// 检查图片是否存在
		boolean isExists = false;
		String mainImage = "original.jpg";
		File[] filelist = file.listFiles();
		if(filelist!=null && filelist.length > 0){
			for (File file2 : filelist) {
				String timeImageName = file2.getName();
				String imageName = file2.getName();
				imageName = imageName.substring(0 , imageName.lastIndexOf("."));
				if(imageName.equals("original")){
					mainImage = timeImageName;
					isExists = true;
				}
			}
		}
		
		String p =  "" ;
		
		if(uptype.equals("1")){
			p =  Constants.BASE_DIR + "/"+ Constants.USER_FILENAME + "/" + fileBookName + "/" + mainImage ;
			if(isTimeFile == true){ // 临时文件夹
				p =  Constants.BASE_DIR + "/"+ Constants.USER_FILENAME + "/timeUserFile/" + fileBookName + "/" + mainImage ;
			}
		}else if(uptype.equals("2")){
			p =  Constants.BASE_DIR + "/"+ Constants.COMPANY_FILENAME + "/" + fileBookName + "/" + mainImage ;
			if(isTimeFile == true){ // 临时文件夹
				p =  Constants.BASE_DIR + "/"+ Constants.COMPANY_FILENAME + "/timeUserFile/" + fileBookName + "/" + mainImage ;
			}
		}
		
		// 创建默认图片
		if(isExists == false){
			try {
				    
					String newFilePath = filePath + File.separator + mainImage;
					
				    String defaultPath = "cts/images/original.jpg";
					FileInputStream fin = null;
					FileOutputStream fout = null;
					
					fin = new FileInputStream(ServletActionContext.getServletContext().getRealPath(defaultPath));
					fout = new FileOutputStream(newFilePath);
					
					byte[] b = new byte[512];
					int n;
					while((n = fin.read(b))!=-1){
						fout.write(b,0,n);
					}
					
					fin.close();
					fout.close();
					
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
        // 取得图片的宽与高
		File whFile = new File(ServletActionContext.getServletContext().getRealPath(p));
		if(whFile.exists()){
		  	try {
		  		BufferedImage img = ImageIO.read(whFile);
		  		int width = img.getWidth();
		  		int height = img.getHeight();
		  		
		  		request.setAttribute("width", width);
		  		request.setAttribute("height", height);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		request.setAttribute("imgName", mainImage);
		request.setAttribute("imgUrl", p);
		request.setAttribute("companyid", companyid);
		request.setAttribute("userid", userId);
		request.setAttribute("uptype", uptype);
		request.setAttribute("isTimeFile", isTimeFile);
		request.setAttribute("fileBookName", fileBookName);
		request.setAttribute("thisTime", System.currentTimeMillis());
		request.setAttribute("reload", reload);
		
		return "imgtool/uploadImg";
	}
	
	
	/**
	 * 上传图片 
	 */
	@Action("upLoadMainImage")
	public void upLoadMainImage(){
		HttpServletRequest request = ServletActionContext.getRequest();
		
		String userId = request.getParameter("userid");
		String companyId = request.getParameter("companyid");
		String uptype = request.getParameter("uptype");
		String isTimeFile = request.getParameter("isTimeFile");
		String fileBookName = request.getParameter("fileBookName");
		
		String extName = null;
		String returnParam = "";
		String imageName = "original";
		String imagePath = "";
		User user = null;
		Company company = null;
		
		if(isTimeFile.equals("true")){ // 使用临时文件夹
			if(uptype.equals("1")){
	        	   // 图片路径
	        	   imagePath = ServletActionContext.getServletContext().getRealPath(
	        			   File.separator + Constants.BASE_DIR + 
	        			   File.separator + Constants.USER_FILENAME + 
	        			   File.separator + "timeUserFile" +
	        			   File.separator + fileBookName);
	         }else if(uptype.equals("2")){
	               //  图片路径
	        	   imagePath = ServletActionContext.getServletContext().getRealPath(
	        			   File.separator + Constants.BASE_DIR + 
	        			   File.separator + Constants.COMPANY_FILENAME + 
	        			   File.separator + "timeUserFile" +
	        			   File.separator + fileBookName);
	        }
		}else{
           if(uptype.equals("1")){
        	   user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId));
        	   // 图片路径
        	   imagePath = ServletActionContext.getServletContext().getRealPath(
        			   File.separator + Constants.BASE_DIR + 
        			   File.separator + Constants.USER_FILENAME + 
        			   File.separator + user.getId());
           }else if(uptype.equals("2")){
        	   company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyId));
               //  图片路径
        	   imagePath = ServletActionContext.getServletContext().getRealPath(
        			   File.separator + Constants.BASE_DIR + 
        			   File.separator + Constants.COMPANY_FILENAME + 
        			   File.separator + companyId);
           }
		}
		
		
		File imageFile = new File(imagePath);
		if(!imageFile.exists()){
			imageFile.mkdirs();
		}
		
		// 图片大小 
		int size = Filedata.size();
		
		if(size == 0){
			ActionUtil.outputData("-1");
			return;
		}
		
		extName = FiledataFileName.get(0).substring(FiledataFileName.get(0).lastIndexOf("."));
		if(extName.toLowerCase().equals(".bmp") || extName.toLowerCase().equals(".png")){
			extName = ".jpg";
		}
		
		File file = new File(imagePath + File.separator + imageName + extName);
		deleteFileIfExist(imagePath , imageName);
		
		try{
			FileUtils.copyFile(Filedata.get(0), file);
			
			String fileName = imageName + extName;
			File dst = new File(imagePath + File.separator + fileName);
			BufferedImage image = ImageIO.read(dst);
			
			int width = image.getWidth();
			int height = image.getHeight();
			
			if(isTimeFile.equals("true")){ // 使用临时文件夹
				if(uptype.equals("1")){
					returnParam = Constants.BASE_DIR + "/" + Constants.USER_FILENAME + "/timeUserFile/" + fileBookName + "/" + fileName + "," + width + "," + height + "," + fileName;
				}else if(uptype.equals("2")){
					returnParam = Constants.BASE_DIR + "/" + Constants.COMPANY_FILENAME + "/timeUserFile/" + fileBookName + "/" + fileName + "," + width + "," + height + "," + fileName;
				}
			}else{
				if(uptype.equals("1")){
					returnParam = Constants.BASE_DIR + "/" + Constants.USER_FILENAME + "/" + user.getId() + "/" + fileName + "," + width + "," + height + "," + fileName;
				}else if(uptype.equals("2")){
					returnParam = Constants.BASE_DIR + "/" + Constants.COMPANY_FILENAME + "/" + company.getId() + "/" + fileName + "," + width + "," + height + "," + fileName;
				}
			}
		    
			ActionUtil.outputData(returnParam);
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * 裁剪图片并且保存为头像
	 *
	 */
	@Action("cutMainImage")
	public void cutMainImage(){
		HttpServletRequest request = ServletActionContext.getRequest();
		
		String userId = request.getParameter("userid");
		String companyId = request.getParameter("companyid");
		String uptype = request.getParameter("uptype");
		String isTimeFile = request.getParameter("isTimeFile");
		String fileBookName = request.getParameter("fileBookName");
		User user = null;
		Company company = null;
		
		if(!isTimeFile.equals("true")){
			if(uptype.equals("1")){
				user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId));
			}else if(uptype.equals("2")){
				company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyId));
			}
		}
		
		String fileName = request.getParameter("fileName");
		long currentTime = System.currentTimeMillis();
		String imageName = "mp_original_" + currentTime;
		String vImageName = imageName;
		String filePath = "";
		
		int width = 150;
		// 获取缩放和剪切参数
		String cutPos = request.getParameter("cut_pos");
		String[] pos = cutPos.split(",");
		// 左上角坐标
		int x = Integer.parseInt(pos[0]);
		int y = Integer.parseInt(pos[1]);
		// 缩放后的图片宽度
		int picWidth = Integer.parseInt(pos[2]);
		int picHeight = Integer.parseInt(pos[3]);
		
		if(fileName != null && fileName.indexOf(".") > 0){
			fileName = imageName + fileName.substring(fileName.indexOf("."));
		}else{
			return;
		}
		
		String newFileName = ServletActionContext.getServletContext().getRealPath("/") + request.getParameter("cut_url");
		if(newFileName.indexOf("?time") > 0){
			newFileName = newFileName.substring(0, newFileName.indexOf("?time"));
		}
		
		if(isTimeFile.equals("true")){ // 临时文件夹
			if(uptype.equals("1")){
				filePath = ServletActionContext.getServletContext().getRealPath(
						   File.separator + Constants.BASE_DIR + 
						   File.separator + Constants.USER_FILENAME +
						   File.separator + "timeUserFile" +
						   File.separator + fileBookName + File.separator);
			}else if(uptype.equals("2")){
				filePath = ServletActionContext.getServletContext().getRealPath(
						   File.separator + Constants.BASE_DIR + 
						   File.separator + Constants.COMPANY_FILENAME +
						   File.separator + "timeUserFile" +
						   File.separator + fileBookName + File.separator);
			}
		}else{ 
			if(uptype.equals("1")){
				filePath = ServletActionContext.getServletContext().getRealPath(
						   File.separator + Constants.BASE_DIR + 
						   File.separator + Constants.USER_FILENAME +
						   File.separator + user.getId() + File.separator);
			}else if(uptype.equals("2")){
				filePath = ServletActionContext.getServletContext().getRealPath(
						   File.separator + Constants.BASE_DIR + 
						   File.separator + Constants.COMPANY_FILENAME +
						   File.separator + company.getId() + File.separator);
			}
		}

		String zoomFile = filePath + File.separator + fileName;
		try {
			new ZoomImage().zoomTheImage(newFileName, zoomFile, picWidth, picHeight);
			OperateImage o = new OperateImage(x, y, width, width);
			o.setSrcpath(zoomFile);
			o.setSubpath(zoomFile);
			o.cut(fileName.substring(fileName.indexOf(".") + 1));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// 清空旧图片,记录新图片路径
		try{
			File oldFile = new File(filePath);
			if(oldFile.exists()){
				File[] list = oldFile.listFiles();
				if(list != null){
					for(File oldSinFile: list){
						Pattern p = Pattern.compile("mp_original_");
						Matcher m = p.matcher(oldSinFile.getName());
						if(m.find()){
							String stImgName = oldSinFile.getName();
							stImgName = stImgName.substring(0, stImgName.indexOf("."));
							if(!stImgName.equals(vImageName)){
								oldSinFile.delete();
							}
						}
						
					}
				}
			}
			
			
			String returnParam = "";
			if(isTimeFile.equals("true")){ // 使用临时文件夹
				if(uptype.equals("1")){
					returnParam = Constants.BASE_DIR + "/" + Constants.USER_FILENAME + "/timeUserFile/" + fileBookName + "/" + fileName + "," + fileName;
				}else if(uptype.equals("2")){
					returnParam = Constants.BASE_DIR + "/" + Constants.COMPANY_FILENAME + "/timeUserFile/" + fileBookName + "/" + fileName + "," + fileName;
				}
			}else{
				if(uptype.equals("1")){
					returnParam = Constants.BASE_DIR + "/" + Constants.USER_FILENAME + "/" + user.getId() + "/" + fileName + "," + fileName;
					user.setLogoPath(fileName);
					this.commonManager.modifyEntity(user);
					CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_logopath", fileName , "/", 24 * 60 * 60 );
				}else if(uptype.equals("2")){
					returnParam = Constants.BASE_DIR + "/" + Constants.COMPANY_FILENAME + "/" + company.getId() + "/" + fileName + "," + fileName;
					company.setLogoPath(fileName);
					this.commonManager.modifyEntity(company);
					CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_companyLogoPath", fileName, "/", 24 * 60 * 60 );
				}
			}
			
			ActionUtil.outputData(returnParam);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	/**
	 * 如果指的文件夹路径不存在，则创建文件夹 如果指定文件夹路径的文件已存在，则删
	 * @param fileFolder 文件夹路径
	 * @param fileName 文件名
	 */
	private void deleteFileIfExist(String fileFolder, String fileName){
		File dst = new File(fileFolder);
		if(!dst.isDirectory()){
			dst.mkdirs();
		}
		File[] list = dst.listFiles();
		if(list != null){
			for(File file: list){
				if(!file.isDirectory()){
					String theName = file.getName();
					theName = theName.substring(0, theName.lastIndexOf("."));
					if(fileName.equals(theName)){
						file.delete();
						break;
					}
				}

			}
		}
	}
	
	
	public CommonManager getCommonManager() {
		return commonManager;
	}

	public void setCommonManager(CommonManager commonManager) {
		this.commonManager = commonManager;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public IUserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(IUserManager userManager) {
		this.userManager = userManager;
	}

	public ICompanyManager getCompanyManager() {
		return companyManager;
	}

	public void setCompanyManager(ICompanyManager companyManager) {
		this.companyManager = companyManager;
	}

	public List<File> getFiledata() {
		return Filedata;
	}

	public void setFiledata(List<File> filedata) {
		Filedata = filedata;
	}

	public List<String> getFiledataContentType() {
		return FiledataContentType;
	}

	public void setFiledataContentType(List<String> filedataContentType) {
		FiledataContentType = filedataContentType;
	}

	public List<String> getFiledataFileName() {
		return FiledataFileName;
	}

	public void setFiledataFileName(List<String> filedataFileName) {
		FiledataFileName = filedataFileName;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public IEmployeeManager getEmployeeManager() {
		return employeeManager;
	}

	public void setEmployeeManager(IEmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}


	
}
